package com.tbit.uqbike.tergateway.jt808;

import com.alibaba.fastjson.JSONObject;
import com.tbit.uqbike.protocol.AnalyzeImpl.AProtocol;
import com.tbit.uqbike.protocol.AnalyzeImpl.Jt808DeEnCoder;
import com.tbit.uqbike.tergateway.config.TerGatewayConfig;
import com.tbit.uqbike.tergateway.data.TerGatewayData;
import com.tbit.uqbike.tergateway.entity.AConnInfo;
import com.tbit.uqbike.tergateway.entity.TerPointData;
import com.tbit.uqbike.tergateway.jt808.entity.BaseItem;
import com.tbit.uqbike.tergateway.pojo.TerPoint;
import com.tbit.uqbike.util.ConstDefine;
import com.tbit.uqbike.util.StringUtil;
import io.netty.buffer.ByteBuf;

import java.util.LinkedList;
import java.util.List;

/**
 * @author MyWin E-mail:335918956@qq.com
 * @version 1.0
 * @createTime 2019-10-30 15:02
 */
public class DataUpPkg extends CommPkg {
    private static org.slf4j.Logger logger = org.slf4j.LoggerFactory.getLogger(DataUpPkg.class);

    public List<BaseItem> itemList = new LinkedList<>();

    @Override
    public void doBusiness() {
        logger.debug(JSONObject.toJSONString(this));
        TerGatewayData.statDataTask.addStatData(TerGatewayConfig.pointDataStatKey, getTerPointDataMsg(this));
    }

    public static String getTerPointDataMsg(DataUpPkg dataUpPkg) {
        TerPointData data = new TerPointData();
        data.mno = dataUpPkg.mno;
        data.datas = new LinkedList<>();
        for (BaseItem item : dataUpPkg.itemList) {
            TerPoint tp = item.toTp(data.mno);
            data.datas.add(tp);
        }

        JSONObject jsonObject = new JSONObject();
        jsonObject.put("msgId", ConstDefine.MQ_MSG_ID_TER_PP);
        jsonObject.put("feedback", StringUtil.Empty);
        jsonObject.put("data", data);
        return jsonObject.toJSONString();
    }

    @Override
    public boolean autoRsp() {
        return true;
    }

    @Override
    public ByteBuf getRsp(AConnInfo conn, AProtocol protocol) {
        return ((Jt808DeEnCoder) protocol).getDataUpRsp(conn, this);
    }
}
